package com.demo.service;

import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.faces.context.FacesContext;

/**
 * User: yuebo
 * Date: 13-9-1
 * Time: 下午3:54
 */
@Service
public class AuthenticationService {
    @Autowired
    private AuthenticationManager authenticationManager;

    public boolean login(String username,String password){
        try{
            Authentication authentication= authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
            if(authentication.isAuthenticated()){
                SecurityContextHolder.getContext().setAuthentication(authentication);
                return true;
            }
        }catch (AuthenticationServiceException e){
            return false;
        }catch (BadCredentialsException exception){
            return false;
        }


        return false;
    }
    @Autowired
    private UserMapper userMapper;

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    @Transactional
    public String getUserPassword(){
        return userMapper.getUser("xyb").getUsername();
    }
}
